#pragma once

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <pthread.h>

#include "thread.hpp"
#include "log.hpp"
#include "LockGuard.hpp"


using namespace ThreadModle;
using namespace log_ns;

static int num = 5;

template <class T>
class ThreadPool
{
private:
    void queue_lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void queue_unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void wakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    bool IsEmpty()
    {
        return _task_queue.empty();
    }

    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    void HanderTask(const std::string &name)
    {
        while (true)
        {
            queue_lock();
            while (IsEmpty() && _Isrunning) // 任务队列为空，进入休眠
            {
                _sleep_thread_num++;
                LOG(INFO, "thread %s sleep begin!\n", name.c_str());
                Sleep();
                LOG(INFO, "thread %s wakeup!\n", name.c_str());
                _sleep_thread_num--;
            }

            if (IsEmpty() && !_Isrunning) // 任务队列空，并且进程池要退出
            {
                std::cout << name << " quit!" << std::endl;
                queue_unlock();
                LOG(INFO, "thread %s quit!\n", name.c_str());
                break;
            }

            // 有任务，取出
            T t = _task_queue.front();
            _task_queue.pop();
            queue_unlock();

            // 处理任务
            t();
        }
    }

    ThreadPool(int thread_num = num)
        : _thread_num(thread_num), _sleep_thread_num(0), _Isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ThreadPool(const ThreadPool<T> &) = delete;
    void operator=(const ThreadPool<T> &) = delete;

    void Init()
    {
        func_t func = std::bind(&ThreadPool::HanderTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++)
        {
            std::string Threadname = "Thread-" + std::to_string(i + 1);
            _threads.emplace_back(Threadname, func);
            LOG(DEBUG, "construct thread %s done, init success\n", Threadname.c_str());
        }
    }
    void Start()
    {
        _Isrunning = true;
        for (auto &threads : _threads)
        {
            LOG(DEBUG, "start thread %s done.\n", threads.Name().c_str());
            threads.Start();
        }
    }

public:
    void Push(const T task)
    {
        queue_lock();
        if (_Isrunning)
        {
            _task_queue.push(task);
            if (_sleep_thread_num > 0)
                wakeup();
        }
        queue_unlock();
    }

    void Stop()
    {
        queue_lock();
        _Isrunning = false;
        wakeupAll();
        queue_unlock();
        LOG(INFO, "thread pool stop success!\n");
    }

    static ThreadPool<T> *GetInstance()
    {
        if (_tp == nullptr)
        {
            LockGuard lockguard(&_sig_mutex);
            if (_tp == nullptr)
            {
                LOG(INFO, "create threadpool\n");
                _tp = new ThreadPool<T>();
                _tp->Init();
                _tp->Start();
            }
            else
            {
                LOG(INFO, "get threadpool\n");
            }
        }
        return _tp;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _thread_num;

    std::queue<T> _task_queue;
    std::vector<Thread> _threads;

    bool _Isrunning;

    int _sleep_thread_num;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例模式 --- 懒汉实现
    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;
template <class T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;